(function ($) {


  //封装树创建
  $.fn.createTree = function (zSetting, zNodes, callback) {
    //当前对象不存在
    if (this.length === 0) {
      console.error("%c%s%c 对象不存在，请检查", "font-weight:bold;text-decoration:underline", this.selector, "");
      return false;
    }

    //如果有treeContentId，就与左树关联,使右侧内容自已适应，
    //如果没有ID，则自已管自已
    //都会根据setting配置生成树

    var me = this;
    var zTreeObj;
    var treeContentId = null;
    var eleTreeList = $(this);

    eleTreeList.parent().css("position", "relative");


    //假如treeContentId没有传入，并且自身id并不是treeList
    if ((!zSetting.view || !zSetting.view.treeContentId) && this.selector == "#treeList") {
      treeContentId = "#treeContent";
    } else {
      treeContentId = zSetting.view.treeContentId;
    }

    //更改ztree的默认配置，以适合本项目
    var setting = {

      view: {
        showLine: false,
        showIcon: true,
        selectedMulti: false,
        treeContentId: treeContentId,
        dblClickExpand: false
      },
      callback: {

      }

    };

    var eleTreeContent = $(treeContentId);

    setting = $.extend(true, setting, zSetting);

    var oldAddDiyDom;

    if (setting.view.addDiyDom) {
      oldAddDiyDom = setting.view.addDiyDom;
    } else {
      oldAddDiyDom = function () { }
    }

    var newAddDiyDom = function (treeId, treeNode) {
      var icoObj = $("#" + treeNode.tId + "_ico");

      icoObj.bind("click", function () {
        zTreeObj.expandNode(treeNode, null, null, null, true);
      });
    }

    setting.view.addDiyDom = function (treeId, treeNode) {
      newAddDiyDom(treeId, treeNode);
      oldAddDiyDom(treeId, treeNode);
    }

    //如果id不存在，则不管树内容，直接生成树即可
    if (eleTreeContent.length <= 0) {
      zTreeObj = $.fn.zTree.init(this, setting, zNodes);

    } else {

      var oldOnExpand, oldOnCollapse;

      if (setting.callback.onExpand) {
        oldOnExpand = setting.callback.onExpand;
      } else {
        oldOnExpand = function () { }
      }

      if (setting.callback.oldOnCollapse) {
        oldOnCollapse = setting.callback.oldOnCollapse;
      } else {
        oldOnCollapse = function () { }
      }

      //设置展开与关闭的事件
      var addOnExpand = function (treeId, treeNode) {
        //展开树自动调整右侧尺寸
        var eleTreeListOuterWidth = eleTreeList.outerWidth(),
          documentWidth = $(document).width();
        if (eleTreeListOuterWidth > documentWidth / 2) {
          eleTreeList.css("width", documentWidth / 2);
          eleTreeContent.animate({
            "marginLeft": eleTreeList.outerWidth() + 10
          });
        } else {
          eleTreeList.css("width", "auto");
          eleTreeContent.animate({
            "marginLeft": eleTreeListOuterWidth + 10
          });
        }
      };

      var addOnCollapse = function (treeId, treeNode) {
        eleTreeList.css("width", "auto");
        var eleTreeListOuterWidth = eleTreeList.outerWidth(),
          documentWidth = $(document).width();
        if (eleTreeListOuterWidth > documentWidth / 2) {
          eleTreeList.css("width", documentWidth / 2);
          eleTreeContent.animate({
            "marginLeft": eleTreeList.outerWidth() + 10
          });
        } else {
          eleTreeList.css("width", "auto");
          eleTreeContent.animate({
            "marginLeft": eleTreeListOuterWidth + 10
          });
        }
      };

      setting.callback.onExpand = function (treeId, treeNode) {
        addOnExpand(treeId, treeNode);
        oldOnExpand(treeId, treeNode);
      };

      setting.callback.onCollapse = function (treeId, treeNode) {
        addOnCollapse(treeId, treeNode);
        oldOnCollapse(treeId, treeNode);
      };

      zTreeObj = $.fn.zTree.init(this, setting, zNodes);

      //初始化树与树内容布局
      eleTreeContent.css("marginLeft", eleTreeList.outerWidth() + 10);
      //为树设置最大高度
      eleTreeList.css("height", eleTreeContent.height() - parseInt(eleTreeList.css("paddingTop")) - parseInt(eleTreeList.css("paddingBottom")) - parseInt(eleTreeList.css("borderTop")) - parseInt(eleTreeList.css("borderBottom")));
    }

    //回调函数
    if (callback) {
      callback(me);
    }

    return zTreeObj;
  };


  //封装树创建
  $.fn.createTreeScroll = function (zSetting, zNodes, callback) {
    //当前对象不存在
    if (this.length === 0) {
      console.error("%c%s%c 对象不存在，请检查", "font-weight:bold;text-decoration:underline", this.selector, "");
      return false;
    }

    //如果有treeContentId，就与左树关联,使右侧内容自已适应，
    //如果没有ID，则自已管自已
    //都会根据setting配置生成树

    var me = this;
    var zTreeObj;
    var treeContentId = null;
    var eleTreeList = $(this);

    eleTreeList.parent().parent().css("position", "relative");


    //假如treeContentId没有传入，并且自身id并不是treeList
    if ((!zSetting.view || !zSetting.view.treeContentId) && this.selector == "#treeList") {
      treeContentId = "#treeContent";
    } else {
      treeContentId = zSetting.view.treeContentId;
    }

    //更改ztree的默认配置，以适合本项目
    var setting = {

      view: {
        showLine: false,
        showIcon: true,
        selectedMulti: false,
        treeContentId: treeContentId,
        dblClickExpand: false
      },
      callback: {

      }

    };

    var eleTreeContent = $(treeContentId);

    setting = $.extend(true, setting, zSetting);

    var oldAddDiyDom;

    if (setting.view.addDiyDom) {
      oldAddDiyDom = setting.view.addDiyDom;
    } else {
      oldAddDiyDom = function () { }
    }

    var newAddDiyDom = function (treeId, treeNode) {
      var icoObj = $("#" + treeNode.tId + "_ico");

      icoObj.bind("click", function () {
        zTreeObj.expandNode(treeNode, null, null, null, true);
      });
    }

    setting.view.addDiyDom = function (treeId, treeNode) {
      newAddDiyDom(treeId, treeNode);
      oldAddDiyDom(treeId, treeNode);
    }

    //如果id不存在，则不管树内容，直接生成树即可
    if (eleTreeContent.length <= 0) {
      zTreeObj = $.fn.zTree.init(this, setting, zNodes);

    } else {

      var oldOnExpand, oldOnCollapse;

      if (setting.callback.onExpand) {
        oldOnExpand = setting.callback.onExpand;
      } else {
        oldOnExpand = function () { }
      }

      if (setting.callback.oldOnCollapse) {
        oldOnCollapse = setting.callback.oldOnCollapse;
      } else {
        oldOnCollapse = function () { }
      }

      //设置展开与关闭的事件
      var addOnExpand = function (treeId, treeNode) {
        /*				//展开树自动调整右侧尺寸
                var eleTreeListOuterWidth = eleTreeList.outerWidth(),
                  documentWidth = $(document).width();
                if (eleTreeListOuterWidth > documentWidth / 2) {
                  eleTreeList.css("width", documentWidth / 2);
                  eleTreeContent.animate({
                    "marginLeft": eleTreeList.outerWidth() + 10
                  });
                } else {
                  eleTreeList.css("width", "auto");
                  eleTreeContent.animate({
                    "marginLeft": eleTreeListOuterWidth + 10
                  });
                }*/
      };

      var addOnCollapse = function (treeId, treeNode) {
        /*				eleTreeList.css("width", "auto");
                var eleTreeListOuterWidth = eleTreeList.outerWidth(),
                  documentWidth = $(document).width();
                if (eleTreeListOuterWidth > documentWidth / 2) {
                  eleTreeList.css("width", documentWidth / 2);
                  eleTreeContent.animate({
                    "marginLeft": eleTreeList.outerWidth() + 10
                  });
                } else {
                  eleTreeList.css("width", "auto");
                  eleTreeContent.animate({
                    "marginLeft": eleTreeListOuterWidth + 10
                  });
                }*/
      };

      setting.callback.onExpand = function (treeId, treeNode) {
        addOnExpand(treeId, treeNode);
        oldOnExpand(treeId, treeNode);
      };

      setting.callback.onCollapse = function (treeId, treeNode) {
        addOnCollapse(treeId, treeNode);
        oldOnCollapse(treeId, treeNode);
      };

      zTreeObj = $.fn.zTree.init(this, setting, zNodes);

      //初始化树与树内容布局
      eleTreeContent.css("marginLeft", eleTreeList.parent().outerWidth() + 10);
      //为树设置最大高度
      eleTreeList.css("height", eleTreeContent.outerHeight() - parseInt(eleTreeList.parent().css("paddingTop")) - parseInt(eleTreeList.parent().css("paddingBottom")) - parseInt(eleTreeList.parent().css("borderTop")) - parseInt(eleTreeList.parent().css("borderBottom")));
    }

    //回调函数
    if (callback) {
      callback(me);
    }

    return zTreeObj;
  };
  //封装树选择列表创建
  $.fn.createTreeSelectList = function (zSetting, zNodes, callback) {
    //当前对象不存在
    if (this.length === 0) {
      console.error("%c%s%c 对象不存在，请检查", "font-weight:bold;text-decoration:underline", this.selector, "");
      return false;
    }

    var me = this;
    var $me = $(this);
    var zTreeObj;
    var selectedArray;

    var setting = {

      //数据关键词字段配置
      data: {
        key: {
          name: "name",
          //可以像ztree 节点数据保存节点名称一样，也可以保存图片关键词了，默认为image
          image: "image",
          //所有子项的总数，默认total
          total: "total",
          //直接子项的总数，默认count
          count: "count"
        }
      },

      view: {
        dblClickExpand: false,
        //add 在不开启选框模式的情况下，高亮的选择模式，默认为单选
        //如果同时开启选框和高亮多选，将以选框为主，忽略高亮
        enableMultiple: false,
        //add 是否开启自动创建视图面板，默认为开启
        //不开启时，创建视图面板，再绑定到树上面
        enabledPanel: false,
        //多选时限制最大选择数目，默认不限制
        multipleSize: null
      },

      check: {
        //默认单选模式
        chkStyle: "radio",
        radioType: 'all'
      },

      //菜单点击事件
      callback: {
        beforeClick: function (event, treeId, treeNode) {
          selectedArray = zTreeObj.getSelectedNodes();

        },

        onClick: function (event, treeId, treeNode) {

          //如果点击的是展开按钮则，触发展开，不执行其他事件
          if ($(event.target).is(".button")) {
            zTreeObj.expandNode(treeNode);
            event.stopPropagation();
            return false;
          }


          //当开启选框模式时，取消高亮
          if (setting.check && setting.check.enable) {
            zTreeObj.cancelSelectedNode(treeNode);
            return false;
          }

          //高亮单选模式时 enableMultiple为false
          if (!setting.view.enableMultiple) {
            if (selectedArray.length > 0 && selectedArray[0].tId == treeNode.tId) {
              zTreeObj.cancelSelectedNode(treeNode);
            }
            return false;
          }




          //高亮多选模式时enableMultiple为true，multipleSize: 有做限制
          //1.多个选中状态
          //2.选中父级时，全选子集
          //3.点击选中的父级时，取消选中子集
          //4.点击子集时，取消父级的选中状态

          //阻止冒泡自动关闭下拉框
          event.stopPropagation();



          //假如已经达到5个，则不应该再选中，并且字体颜色置灰色,表示无法选中的意思

          //子元素选中状态
          //TODO  循环遍历父亲，和循环遍历子级样式的变化
          var childSelectdState = function (parentNode, handle) {
            if (parentNode.isParent && parentNode.children.length > 0) {
              //是父元素，并且，有子元素，则选中所有子元素

              if (handle) {
                for (var j = 0; j < parentNode.children.length; j++) {
                  zTreeObj.selectNode(parentNode.children[j], true);
                }
              } else {
                for (var j = 0; j < parentNode.children.length; j++) {
                  zTreeObj.cancelSelectedNode(parentNode.children[j]);
                }
              }
            }
          }


          //高亮多选模式，高亮模式和选框模式同时开启时，优先以选框模式为准
          if (setting.view && setting.view.enableMultiple && (setting.check && !setting.check.enable)) {
            //多选选中目前已选中的项
            for (var i = 0; i < selectedArray.length; i++) {
              zTreeObj.selectNode(selectedArray[i], true);
            }

            //判断当前项是否已被选中，若已选中，则取消当前项高亮
            //若当是父亲且存在子项，还要取消选中他的孩子
            //若当前项有父亲且兄弟项未全部选中，则迭代取消其父亲的高亮选中
            if ($.inArray(treeNode, selectedArray) >= 0) {
              //取消，取消子级
              zTreeObj.cancelSelectedNode(treeNode)
              childSelectdState(treeNode, false)
            } else {
              childSelectdState(treeNode, true)
            }
          }

          //截断选中队列数
          //判断当前选中数和多选限制数,超过时，变更样式
          if (setting.view.multipleSize && setting.view.multipleSize <= zTreeObj.getSelectedNodes().length) {
            $me.addClass("multipleSize");

          } else {
            $me.removeClass("multipleSize");
          }

          if (setting.view.multipleSize && zTreeObj.getSelectedNodes().length > setting.view.multipleSize) {
            zTreeObj.cancelSelectedNode(treeNode)

          }




        }

      }
    };

    //回调函数
    if (callback) {
      callback(me);
    }

    //覆盖配置
    setting = $.extend(true, setting, zSetting);

    //自定义dom树关键字名称
    var parentOffset = 0;
    var selfOffset = 0;


    //配置容错
    if (setting.view.multipleSize === 0 || setting.view.multipleSize === 1) {
      setting.view.multipleSize = null;
    }
    //自定义dom树结构
    setting.view.addDiyDom = function (treeId, treeNode) {

      var checkObj = $("#" + treeNode.tId + "_check"),
        icoObj = $("#" + treeNode.tId + "_ico"),
        switchObj = $("#" + treeNode.tId + "_switch"),
        spanObj = $("#" + treeNode.tId + "_span");

      var spanObjHtml = "";

      //若开启选择框
      if (setting.check && setting.check.enable) {
        icoObj.after(checkObj);
        switchObj.remove();
        spanObj.css("display", "inline-block");
      } else {
        switchObj.remove();
      }

      if (treeNode[setting.data.key.name]) {
        spanObjHtml += treeNode[setting.data.key.name];
      }
      if (treeNode[setting.data.key.total]) {
        spanObjHtml += "(" + treeNode[setting.data.key.total] + ")";
      }
      if (treeNode[setting.data.key.count]) {
        spanObjHtml += "(" + treeNode[setting.data.key.count] + ")";
      }

      //若存在图片
      if (treeNode[setting.data.key.image]) {
        spanObjHtml = "<img class='icon-image' src ='" + treeNode[setting.data.key.image] + "' / ><span class='icon-text' >" + spanObjHtml + "</span>"
      }

      spanObj.attr("data-parentOffset", parentOffset)
      spanObj.attr("data-selfOffset", selfOffset)
      parentOffset++;
      selfOffset++;
      spanObj.html(spanObjHtml);
    }

    //创建树
    zTreeObj = $.fn.zTree.init(this, setting, zNodes);

    //返回树ID
    zTreeObj.me = "#" + zTreeObj.setting.treeId;
    //返回树配置

    //包裹树
    $me.wrap("<div style='position:relative'></div>");
    //创建视图面板，需要引入panelviewport.js文件
    if (setting.view.enabledPanel) {

      //生成面板dom

      var panelviewport = $('<div id="panelViewport" data-mode="tree" class="tree-select-list-panel panel-viewport"><div class="panel-placeholder">请选择</div><i class="ui-selectbox-icon"></i></div>');
      $me.before(panelviewport);

      panelviewport.panelviewport(zTreeObj, function (that) {
        //选区默认不可见，点击多选框后，才可见，以下语句默认使选区可见
        that.$me.show()
      });
    }

    return zTreeObj;
  };

  //封装按钮下拉
  $.fn.dropList = function () {
    var dropListOption = this;
    this.each(function () {
      var droplistOption = $(this).find(".ui-droplist-option");
      var btn = $(this).find(".btn");
      var icon = $(this).find(".arrow-selectbox-container");
      var btnInnerWidth = btn.innerWidth();
      droplistOption.css({
        "minWidth": btnInnerWidth
      });

      var dropButton = $(this);

      if (dropButton.is(".arrow-droplist")) {
        icon.unbind("click");

        icon.bind("click", function (event) {
          event.stopPropagation();

          if (droplistOption.is(":visible")) {

            btn.removeClass("active");
            droplistOption.hide();
            dropButton.parents(".table").css('marginBottom', 0)
          } else {
            dropListOption.find(".ui-droplist-option").prev().removeClass("active")
            dropListOption.find(".ui-droplist-option").hide();
            btn.addClass("active");
            droplistOption.show();
            if (dropButton.is(".table-droplist")) {
              if (dropButton.position().top + dropButton.outerHeight() + droplistOption.outerHeight() > dropButton.parents(".table").outerHeight()
                && droplistOption.outerHeight() < dropButton.position().top) {
                //按钮位置+按钮高度+弹出层高度大于表可靠高度时,改成向上弹出
                droplistOption.css({
                  position: "absolute",
                  left: dropButton.position().left,
                  //边框高度-按钮位置=剩余的量，剩余的量
                  bottom: dropButton.parents(".table").outerHeight() - dropButton.position().top
                });
              } else {
                var maring_bottom = dropButton.position().top + dropButton.outerHeight() + droplistOption.outerHeight() - dropButton.parents(".table").outerHeight() - dropButton.parents(".table").next().outerHeight();
                if (maring_bottom > 0) {
                  dropButton.parents(".table").css('marginBottom', maring_bottom)
                }
                droplistOption.css({
                  position: "absolute",
                  left: dropButton.position().left,
                  top: dropButton.position().top + dropButton.outerHeight()
                });
              }
            }
          }
        });

      } else {
        dropButton.unbind("click");
        dropButton.bind("click", function (event) {
          //TABLE下拉框出现兼容
          event.stopPropagation();

          if (droplistOption.is(":visible")) {
            btn.removeClass("active");
            droplistOption.hide();
            dropButton.parents(".table").css('marginBottom', 0)
          } else {
            dropListOption.find(".ui-droplist-option").prev().removeClass("active")
            dropListOption.find(".ui-droplist-option").hide();
            btn.addClass("active");
            droplistOption.show();
            if (dropButton.is(".table-droplist")) {
              if (dropButton.position().top + dropButton.outerHeight() + droplistOption.outerHeight() > dropButton.parents(".table").outerHeight()
                && droplistOption.outerHeight() < dropButton.position().top) {
                //按钮位置+按钮高度+弹出层高度大于表可靠高度时,改成向上弹出
                droplistOption.css({
                  position: "absolute",
                  left: dropButton.position().left,
                  //边框高度-按钮位置=剩余的量，剩余的量
                  bottom: dropButton.parents(".table").outerHeight() - dropButton.position().top
                });
              } else {
                var maring_bottom = dropButton.position().top + dropButton.outerHeight() + droplistOption.outerHeight() - dropButton.parents(".table").outerHeight() - dropButton.parents(".table").next().outerHeight();
                if (maring_bottom > 0) {
                  dropButton.parents(".table").css('marginBottom', maring_bottom)
                }
                droplistOption.css({
                  position: "absolute",
                  left: dropButton.position().left,
                  top: dropButton.position().top + dropButton.outerHeight()
                });
              }
            }
          }
        });
      }
    });
    //点击空白区域关闭选框事件
    $("html").click(function () {
      //查找所有的ui-droplist
      dropListOption.find(".ui-droplist-option").prev().removeClass("active")
      dropListOption.find(".ui-droplist-option").hide();
    });
  };

  //封装弹出小提示
  $.fn.popupTips = function () {
    var tips = this;
    tips.each(function () {
      if ($(this).is(".popuptips")) {
        $(this).bind("click", function (event) {
          var content = $(this).attr("title");
          layer.tips(content, $(this), {
            tips: 2,
            time: 5000
          });
          event.stopPropagation();
        });
      } else if ($(this).is(".showtips")) {

        $(this).bind("click", function (event) {

          var tipsid = $(this).attr("data-tipsid");
          var $info;
          if (tipsid && $(tipsid).length > 0) {
            //展示html内容
            $info = $(tipsid);
            if ($info.is(":visible")) {
              $info.fadeOut()
            } else {
              $info.fadeIn()
            }
          } else {
            //根据title创建html元素
            var content = $(this).attr("title");
            if ($(this).next().length <= 0) {
              $info = $('<div class="showtips-alert alert alert-warning mb-10"><span>' + content + '</span><span class="tips-close"><i class="iconfont">&#xe628;</i></span></div>');
              $(this).after($info);
              $info.fadeIn();
            } else {
              $info = $(this).next();
              if ($info && $info.is(":visible")) {
                $info.fadeOut()
              } else if ($info) {
                $info.fadeIn();
              }
            }
          }

          //为关闭按钮添加事件
          if ($info && $info.is(":visible")) {
            $info.delegate(".tips-close", "click", function () {
              event.stopPropagation();
              $info.fadeOut();
            });
          }
          event.stopPropagation();
        });
      }
    })
  };

  //封装文本域字数统计
  //字数统计以html里设置的maxLength为最高优先级，参数无法覆盖它
  $.fn.wordCount = function (maxlength) {
    this.each(function () {
      //如果HTML标签存在maxlength属性，则以maxlength
      //如果不存在maxlength属性，则以maxlength参数为准

      var maxlengthP = $(this).attr("maxlength");
      var endlength = 0;
      //参数校验
      if (maxlengthP && maxlengthP > 0) {
        endlength = parseInt(maxlengthP);
      } else if (maxlength && parseInt(maxlength) > 0) {
        endlength = parseInt(maxlength)
        $(this).attr("maxlength", endlength);
      } else {
        return false;
      }

      //创建统计数对象
      var countHtml = $("<span>0/" + endlength + "</span>").insertAfter($(this));
      //将目标框之后的所有内容包裹，
      $(this).nextAll().wrapAll("<div style='position:relative;display:inline-block;vertical-align:top;margin-left:4px;height:" + $(this).outerHeight() + "px;'></div>");
      countHtml.css({
        position: "absolute",
        left: 0,
        bottom: 0,
        color: "#d9534f"
      });

      //判断字数,在键盘按下之时，内容输出之前
      $(this).keyup(function () {
        var nowLength = $(this).val().length;
        //显示到P里
        countHtml.text(nowLength + "/" + endlength);
      });
      $(this).keyup();
    });
  };

  //封装tabs页
  $.fn.tabs = function (setting) {

    //切换后返回的id值 C
    //点击次数，是否已加载 C
    //增加数据 C
    //onclick返回事件 C

    var me = this;

    var config = {
      store: {
        /*data: [{
          id: "01",
          target: "#tab1",
          name: "学生信息",
          state: "selected"
          }, {
          id: "02",
          target: "#tab2",
          name: "教师信息",
          }, {
          id: "03",
          target: "#tab3",
          name: "家长信息",
          }]*/
      },
      view: {

      },
      callback: {
        /*nodeOnClick: function ($currentNode, $currentData) {
        }*/
      }
    }

    config = $.extend(true, config, setting);

    //由类名tabs控制为一组，检测项中的selected状态
    var $node = $(this).find('.node');

    //初始化进入配置选中

    //html形式书写并且data不存在时
    if ($node.length > 0 && !config.store.data) {
      //缓存html节点上的数据 id和名称,选中状态，和目标
      $node.each(function (i) {
        var currentNode = $(this);
        var currentNodeData = {};
        currentNodeData.id = currentNode.attr("id");
        currentNodeData.target = currentNode.attr("data-target");
        currentNodeData.name = currentNode.get(0).innerText;
        if (currentNode.attr("class").match("selected")) {
          currentNodeData.state = "selected";
        }
        currentNode.data("data", currentNodeData);
      })
    } else {
      //清空原数据
      $(this).empty();
      //按配置生成html元素内容

      for (var i = 0; i < config.store.data.length; i++) {
        var $node2 = $('<div class="node" id="' + config.store.data[i].id + '" data-target="' + config.store.data[i].target + '">' + config.store.data[i].name + '</div>');

        if (config.store.data[i].state == "selected") {
          $node2.addClass("selected")
        }

        //绑定数据
        $node2.data("data", config.store.data[i]);

        $(this).append($node2);
      }
    }

    $(this).delegate('.node', 'click', function (event) {
      var $node = $(me).find('.node');
      //样式变化
      $node.removeClass('selected');
      $(this).addClass('selected');

      //打开项显示
      $($(this).attr('data-target')).siblings().hide()
        .end().show();

      //点击数增加，返回数据
      if (!$(this).data("data").count && $(this).data("data").count != 0) {
        $(this).data("data").count = 0;
      } else {
        $(this).data("data").count++
      }


      if (config && config.callback && config.callback.nodeOnClick && $.type(config.callback.nodeOnClick) == "function") {
        config.callback.nodeOnClick($(this), $(this).data("data"));
      }
    });

    //自定义链接参数进入选中
    var params = getUrlParams();
    if (params.id) {
      $(this).find("#" + params.id).click();
    }

  };

  //即时搜索下拉框
  $.fn.searchDroplist = function (controllerO, filterKey, matchMode) {
    var searchO = $(this)
    var ncO, dlO;

    if ($.type(controllerO) == "array") {
      dlO = controllerO[0];
      if (controllerO[1]) {
        ncO = controllerO[1];
      }
    } else {
      dlO = controllerO;
    }

    var $search = searchO;
    var $dl = dlO.$me;
    var $nc = ncO ? ncO.me : null;

    //初始化UI
    $search.parent().css({
      "position": "relative"
    });

    //假如搜索区初始化无内容，则显示下拉列表中已选中的数据
    if (!$search.val() && dlO.getSelectedNode().length > 0) {
      if (dlO.config.view.enabledMultiple) {
        //多选
        $search.val(dlO.dataToArray(dlO.getSelectedData("name")).join(","))
      } else {
        $search.val(dlO.dataToArray(dlO.getSelectedData("name"))[0])
      }
    }

    //取消节点的全部选中状态
    dlO.cleanSelectedNode();

    if (dlO.config.view.enabled) {
      //搜索区获取焦点事件
      $search.bind("focus", function () {
        $(".close-popup").hide();
        if (ncO) {
          $nc.show();
          $dl.show();
          $nc.css({
            "position": "absolute",
            "width": $search.outerWidth() + "px",
            "left": 0,
            "top": $search.outerHeight(),
            "zIndex": 1024
          })
          ncO.autohidedom.css({
            "zIndex": 1030
          });
        } else {
          $dl.show();
          $dl.css({
            "position": "absolute",
            "width": $search.innerWidth() + "px",
            "height": "288px",
            "overflowY": "auto",
            "left": 0,
            "top": $search.outerHeight(),
            "zIndex": 1024
          })
        }
      });


      //搜索键盘 keyup事件
      //连字查找时，字之间需要无空格
      $search.bind("keyup", function () {
        var searchVal = $search.val();

        var $allNode = dlO.getAllNode();
        if (searchVal.length > 0) {
          var resultNodeId = dlO.filterNode(searchVal)
          if (resultNodeId.length > 0) {
            $allNode.hide();
            resultNodeId.show();

            if (ncO) {
              $nc.show();
              var ncHeight = $nc.height();
              //判断内容区高度
              if ($dl.height() < ncHeight) {
                ncO.autohidedom.hide()
              }
            } else {
              $dl.show();
              //取得现有的高度值
              var currentHeight = $dl.css("height");
              $dl.css({
                "height": "auto"
              })
              if (parseInt($dl.css("height")) < parseInt(currentHeight)) {
                $dl.css({
                  "overflowY": "hidden"
                })
              }
            }
          } else {
            if (ncO) {
              $nc.hide();
            } else {
              $dl.hide();
            }
          }
        } else {
          $allNode.show();

          if (ncO) {
            $nc.show();
            ncO.autohidedom.show()
          } else {
            $dl.show();
            $dl.css({
              "overflowY": "auto",
              "maxHeight": "288px"
            })
          }
        }
      });

      /*
      $search.bind("keyup", function () {
        var searchVal = "";
        if (matchMode && $.type(matchMode) == "boolean") {
          searchVal = $.trim($search.val()).replace(/\s+/g, "");
          var regString = "";
          for (var i = 0; i < searchVal.length; i++) {
            regString += searchVal[i] + "+.*";
          }
          searchVal = regString;
        } else {
          searchVal = $.trim($search.val()).replace(/\s+/g, " ");
          searchVal = searchVal.replace(/\s+/g, "+.*");
        }
        var $allNode = dlO.getAllNode();
        if (searchVal.length > 0) {
          var resultNodeId = [];

          for (var i = 0; i < $allNode.length; i++) {
            var $getNode = $allNode.eq(i)
            var getData;
            //字符串，或者数组
            if (filterKey && filterKey == "all") {
              getData = dlO.getDataById($getNode);
            } else if (filterKey && ($.type(filterKey) == "string" || $.type(filterKey) == "array")) {
              getData = dlO.getDataById($getNode, filterKey);
            } else {
              getData = dlO.getDataById($getNode, "name");
            }
            for (var key in getData) {
              if ($.trim(getData[key]).search(eval("/" + searchVal + "/g")) >= 0) {
                resultNodeId.push(dlO.getDataById($getNode).id)
                continue;
              }
            }
          }

          if (resultNodeId.length > 0) {
            $allNode.hide();
            dlO.getNodeById(resultNodeId).show();

            if (ncO) {
              $nc.show();
              var ncHeight = $nc.height();
              //判断内容区高度
              if ($dl.height() < ncHeight) {
                ncO.autohidedom.hide()
              }
            } else {
              //取得现有的高度值
              var currentHeight = $dl.css("height");
              $dl.css({
                "height": "auto",
              })
              if (parseInt($dl.css("height")) < parseInt(currentHeight)) {
                $dl.css({
                  "overflowY": "hidden",
                })
              }
            }
          } else {
            if (ncO) {
              $nc.hide();
            } else {
              $dl.hide();
            }
          }
        } else {
          $allNode.show();

          if (ncO) {
            $nc.show();
            ncO.autohidedom.show()
          } else {
            $dl.show();
            $dl.css({
              "overflowY": "auto",
              "maxHeight": "288px"
            })
          }
        }
      });*/
    } else {
      $search.attr("disabled", "disabled");
    }

    //搜索区点击事件：阻止冒泡
    $search.bind("click", function (event) {
      event.stopPropagation();
    })

    //节点点击事件

    dlO.$content.delegate("[data-role='node']", "click", function (event) {

      //如果项不可选，则直接退出
      if (dlO.getDataById($(this)).state == "disabled") {

        return false;

      }
      //多选
      if (dlO.config.view.enabledMultiple) {
        event.stopPropagation();
        var nodeName = dlO.getDataById($(this)).name;
        //拼装到原来已有的内容里
        var searchText = "";
        if (!$search.val()) {
          searchText = nodeName;
        } else {
          searchText = $search.val() + "," + nodeName;
        }
        $search.val(searchText);
        dlO.cancelSelectedNode($(this));
        searchO.focus();

      } else {
        //单选
        var nodeName = dlO.getDataById($(this)).name;
        $search.val(nodeName);
        dlO.cancelSelectedNode($(this))
      }

    });


    //点击空白区域关闭选框事件
    $("html").click(function () {
      $(".close-popup").hide();

    });
  };

  //初始化图片管理组件
  $.fn.imgListinit = function (option) {
    //初始化
    var _t = '',
      ops = {};

    ops._file = option.file || '#file_upload';//上传绑定文件组件
    ops._text = option.text || '点击上传';//返回结果容器
    ops._swf = option.swf || 'uploadify.swf';//上传swf地址
    ops._uri = option.uri || '';//图片路径补全
    ops._ajax = option.ajax || '/file/upload.ajax';//上传ajax方法
    ops._sessionId = option.sessionId || '';
    ops._uploader = ops._uri + ops._ajax;//上传ajax路径
    ops._marginRight = option.marginRight || 0;//右间距
    ops._marginLeft = option.marginLeft || 0;//左间距
    ops._marginTop = option.marginTop || 0;//上间距
    ops._marginBottom = option.marginBottom || 0;//下间距
    ops._isBlock = option.isBlock || false;//是否显示为块状化
    ops._width = option.width || '100';//小块宽度
    ops._height = option.height || '100';//小块高度
    ops._conWidth = option.conWidth || '100%';//容器宽度
    ops._drag = option.drag || true;//是否启用拖动
    ops._float = option.float || 'left';//元素浮动
    ops._max = option.max || 999;//上传数量,默认999
    ops._formData = option.formData || null;//上传参数,默认null对象
    ops._data = option.data || null;//初始化数据,编辑时用,默认为空
    ops._multi = option.multi || null;//初始化数据,编辑时用,默认为空
    ops._fileSizeLimit = option.fileSizeLimit || '100MB';
    ops._fileName = option.fileName || 'file';
    ops._fileObjName = option.fileObjName;
    ops._queueSizeLimit = option.queueSizeLimit;
    ops._onUploadSuccess = option.onUploadSuccess || null;
    ops._auto = ops.auto;
    ops._autoBtn = ops.autoBtn;
    if ($(this.selector).find('ul.li_list').length == 0) {
      _t += '<style type="text/css">';
      _t += '.ui-sortable-placeholder.ui-state-highlight{float: left;border:none;width: ' + ops._width + 'px;height:' + ops._height + 'px}';
      _t += '.li_list img{width: 100%;}';
      _t += '.li_list li{position: relative;}';
      _t += '.li_list li a.remove{position: absolute;right:0;top:0;background:#c00;color:#fff;}';
      _t += '.holder{border:1px solid #e00;background: #00e;}';
      _t += '.uploadify-button{color: #fff;backgr ound-color: #417dea;border: 1px solid #366dd1;border-radius: 2px;background-image: none;opacity: 0.9;}';
      _t += '.uploadify:hover .uploadify-button{background: none;background-color: #417dea;opacity: 1;}';
      // if (!$()._isFlash()) {
      _t += 'a.uploadify-button{color: #fff;backgr ound-color: #417dea;border: 1px solid #366dd1;border-radius: 2px;background-image: none;font-weight: ';
      _t += 'bold;background:#505050;opacity: 0.9;margin-bottom: 0px;display: inline-block;width: inherit;}';
      _t += 'a.uploadify-button:hover{background: none;background-color: #417dea;opacity: 1;color:#fff;text-decoration: none;}';
      _t += 'a.uploadify-button:focus{color:#fff;}';
      // }
      _t += '</style>';
      _t += '<ul class="li_list" style="width:' + ops._conWidth + ';overflow:hidden;">';
      if (ops._data != null) {
        //存在默认数据
        var list = ops._data.split(','),
          opt = '';
        opt += 'margin-right:' + ops._marginRight + 'px;margin-left:' + ops._marginLeft + 'px;margin-top:' + ops._marginTop + 'px;margin-bottom:' + ops._marginBottom + 'px;';
        for (var i = 0, l = list.length; i < l; i++) {
          _t += '<li data-url="' + list[i] + '" style="overflow:hidden;width:' + ops._width + ';height:' + ops._height + ';float:' + ops._float + ';' + opt + '"><a href="javascript:;" class="remove">删除</a><a href="' + (ops._uri + list[i]) + '" target="_blank"><img class="single_img" style="' + (ops._isBlock ? 'display:block;' : 'display:inline;') + '" src="' + (ops._uri + list[i]) + '"/></a></li>';
        };

      };
      _t += '</ul>';

      $(this.selector).html(_t);

      //绑定删除函数
      $(this.selector).find('a.remove').unbind('click').click(function () {
        $(this).parent().remove();
      });

      //绑定拖拽
      if (ops._drag != 'false') {
        $(this.selector).find('.li_list').sortable({
          'placeholder': 'ui-state-highlight'
        });
        $(this.selector).find('.li_list').disableSelection();
      };
    };

    return ops;
  };

  $.fn._isFlash = function () {
    try {
      if (typeof window.ActiveXObject != 'undefined') {
        return parseInt((new ActiveXObject('ShockwaveFlash.ShockwaveFlash')).GetVariable("$version").split(" ")[1].split(",")[0], 10);
      } else {
        return parseInt(navigator.plugins["Shockwave Flash"].description.split(' ')[2], 10);
      }
    } catch (e) {
      return 0;
    }
  };

  //封装上传功能
  $.fn.imageLoader = function (option, num) {
    //上传功能
    var o = $(this.selector);
    var ops = this.imgListinit(option);
    var _datas = {
      'auto': ops._auto,
      'buttonText': ops._text,
      'method': 'post',
      'formData': ops._formData,
      'swf': ops._swf,
      'uploader': ops._uploader,
      'uploadLimit': 999,
      'fileTypeExts': '*.gif;*.jpg;*.png;*.jpeg;*.bmp;',
      'fileTypeDesc': '只能上传图片文件',
      'removeTimeout': 0.5,
      'successTimeout': 60 * 60 * 24,
      'file': ops._file,
      'max': ops._max,
      'multi': ops._multi,
      'fileSizeLimit': ops._fileSizeLimit,
      'fileObjName': ops._fileObjName,
      'queueSizeLimit': ops._queueSizeLimit,
      'width': ops._width,
      'height': ops._height,
      'autoBtn': ops._autoBtn,
      onUploadStart: function (file) {
        //判断数量 
        if (o.find('img.single_img').length >= ops._max) {
          alert('上传数目已达极限');
          if ($()._isFlash()) {
            uploader.uploadify('cancel', '*');
          }
        };
      },
      onUploadSuccess: ops._onUploadSuccess || function (file, data, response) {
        data = JSON.parse(data);
        if (data.s == 1) {
          var opt = '';
          opt += 'margin-right:' + ops._marginRight + 'px;margin-left:' + ops._marginLeft + 'px;margin-top:' + ops._marginTop + 'px;margin-bottom:' + ops._marginBottom + 'px;';
          var s = '<li data-url="' + (ops._uri + data.d.savePath) + '" style="overflow:hidden;width:' + ops._width + ';height:' + ops._height + ';float:' + ops._float + ';' + opt + '"><a href="javascript:;" class="remove">删除</a><a href="' + (ops._uri + data.d.savePath) + '" target="_blank"><img class="single_img" style="' + (ops._isBlock ? 'display:block;' : 'display:inline;') + '" src="' + (ops._uri + data.d.savePath) + '"/></a></li>';
          o.find('.li_list').append(s);
          //绑定删除函数
          o.find('a.remove').unbind('click').click(function () {
            $(this).parent().remove();
          });
          if (ops._drag) {
            o.find('.li_list').sortable({
              'placeholder': 'ui-state-highlight'
            });
            o.find('.li_list').disableSelection();
          };
        } else {
          alert(data.d);
        };
      },
      onUploadError: function (file, errorCode, errorMsg, errorString) {
        alert('The file ' + file.name + ' could not be uploaded: ' + errorString);
      }
    }
    if (!$()._isFlash()) {
      var uploader = $(this).Huploadify(_datas);
    } else {
      var uploader = $(ops._file).uploadify(_datas);
    }
    if (!_datas.auto) {
      $.fn.fileLoaderUploadify = function(data){
        if (!$()._isFlash()) {
          uploader.formData = $.extend(_datas.formData,data);
          uploader.allUpload();
        }else{
          $(ops._file).uploadify('settings','formData',data);
          $(ops._file).uploadify('upload', '*');
        }
      }
    }
  };

  //封装返回图片序列功能
  $.fn.getImageList = function (filter) {
    var s = '',
      reg = new RegExp(filter);
    $(this.selector).find('img.single_img').each(function () {
      s += $(this).attr('src').replace(reg, '');
      s += ',';
    });
    return s.substring(0, s.length - 1);
  };

  //封装文件上传功能
  $.fn.fileLoader = function (option) {
    var ops = {},
      _t = '',
      o = $(this.selector);
    ops._file = option.file || '#file_upload';//上传绑定文件组件
    ops._text = option.text || '点击上传';//返回结果容器
    ops._swf = option.swf || 'uploadify.swf';//上传swf地址
    ops._uri = option.uri || '';//路径补全
    ops._ajax = option.ajax || '/file/upload.ajax';//上传ajax方法
    ops._sessionId = option.sessionId || '';
    ops._uploader = ops._uri + ops._ajax + '?_sessionId=' + ops._sessionId;//上传ajax路径
    ops._drag = option.drag || true;//是否启用拖动
    ops._max = option.max || 999;//上传数量,默认999
    ops._formData = option.formData || null;//上传参数,默认null对象
    ops._fileType = option.ftype || '*.*';//上传类型
    ops._data = option.data || null;//初始化数据,编辑时用,默认为空    
    ops._onUploadSuccess = option.onUploadSuccess || null;
    ops._multi = option.multi;
    ops._fileSizeLimit = option.fileSizeLimit || '10MB';
    ops._onUploadError = option.onUploadError || null;
    ops._onUploadStartFun = option.onUploadStartFun || null;
    ops._fileObjName = option.fileObjName;
    ops._queueSizeLimit = option.queueSizeLimit || 999;
    ops._width = option.width || 100;
    ops._height = option.height || 30;
    ops._auto = option.auto;//是否自动上传
    ops._autoBtn = option.autoBtn;
    if (o.find('ul.file_list').length == 0) {
      _t += '<style type="text/css">';
      _t += 'span.fileType_default{background-position:0px -1824px;}';//默认
      _t += 'span.fileType_0{background-position:0px -1232px;}';//work
      _t += 'span.fileType_1{background-position:0px -1696px;}';//text
      _t += 'span.fileType_2{background-position:0px -2112px;}';//ppt
      _t += 'span.fileType_3{background-position:0px -1248px;}';//excel

      _t += '.ui-sortable-placeholder.ui-state-highlight{border:none;width:auto;height:27px;}';
      _t += '.file_list{font-family:"microsoft yahei";width:320px;color:#333;}';
      _t += '.file_list li{width:320px;position: relative;padding:5px 0 6px;overflow: hidden;border-bottom:1px dashed #999;line-height:16px;}';
      _t += '.file_list li span{display:block;float:left;}';
      //_t += '.file_list li span.tag{width:16px;height:16px;overflow: hidden;margin-right:4px;background-image:url("img/buttons.gif");background-repeat:no-repeat;}';
      _t += '.file_list li span.name{width:200px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;}';
      _t += '.file_list li span.control{width:90px;padding-left:10px;overflow: hidden;}';
      _t += '.holder{border:1px solid #e00;background: #00e;}';
      _t += '.uploadify-button{color: #fff;backgr ound-color: #417dea;border: 1px solid #366dd1;border-radius: 2px;background-image: none;opacity: 0.9;}';
      _t += '.uploadify:hover .uploadify-button{background: none;background-color: #417dea;opacity: 1;}';
      if (!$()._isFlash()) {
        _t += '.uploadify-button{color: #fff;backgr ound-color: #417dea;border: 1px solid #366dd1;border-radius: 2px;background-image: none;font-weight: ';
        _t += 'bold;background:#505050;opacity: 0.9;margin-bottom: 0px;display: inline-block;width: inherit;}';
        _t += '.uploadify-button:hover{background: none;background-color: #417dea;opacity: 1;color:#fff;text-decoration: none;}';
        _t += '.uploadify-button:focus{color:#fff;}';
      }
      _t += '</style>';
      _t += '<ul class="file_list" style="width:100%;overflow:hidden;">';
      if (ops._data != null && (ops._data.names != '' && ops._data.paths != '')) {
        //存在默认数据
        var list_name = ops._data.names.split(','),
          list_path = ops._data.paths.split(',');

        for (var i = 0, l = list_name.length; i < l; i++) {
          _t += '<li data-name="' + list_name[i] + '" data-path="' + list_path[i] + '" data-url="' + (ops._uri + list_path[i]) + '">';
          _t += '<span class="tag ' + findType(findLast(list_path[i])) + '">&nbsp;</span>';
          _t += '<span class="name" title="' + list_name[i] + '">' + list_name[i] + '</span>';
          _t += '<span class="control">(<a href="' + (ops._uri + list_path[i]) + '" style="color:#366dd1;">下载</a>&nbsp;|&nbsp;<a href="javascript:;" class="remove" style="color:#c00">删除</a>)</span>';
          _t += '</li>';
        };

      };
      _t += '</ul>';

      o.html(_t);
      //绑定删除函数

      o.find('a.remove').unbind('click').click(function () {
        $(this).parents('li').remove();
      });

      //绑定拖拽
      if (ops._drag != 'false') {
        o.find('.file_list').sortable({
          'placeholder': 'ui-state-highlight'
        });
        o.find('.file_list').disableSelection();
      };
    };

    //实例化上传组件
    var _datas = {
      'auto': ops._auto,
      'buttonText': ops._text,
      'method': 'post',
      'formData': ops._formData,
      'swf': ops._swf,
      'uploader': ops._uploader,
      'queueSizeLimit': ops._queueSizeLimit,
      'uploadLimit': 999,
      'multi': ops._multi,
      'fileTypeExts': ops._fileType,
      'fileTypeDesc': '只能上传特定文件',
      'removeTimeout': 0.5,
      'file': ops._file,
      'max': ops._max,
      'successTimeout': 60 * 60 * 24,
      'fileSizeLimit': ops._fileSizeLimit,
      'fileObjName': ops._fileObjName,
      'width': ops._width,
      'height': ops._height,
      'autoBtn': ops._autoBtn,
      onUploadStart: function (file) {
        //判断数量 
        if (o.find('li').length >= ops._max) {
          alert('上传数目已达极限');
          uploader.uploadify('cancel', '*');
        };
        ops._onUploadStartFun && ops._onUploadStartFun()
      },
      onUploadSuccess: ops._onUploadSuccess || function (file, data, response) {
        data = JSON.parse(data);
        if (data.s == 1) {
          var s = '',
            obj = data.d;
          s += '<li data-name="' + obj.originalFilename + '" data-path="' + obj.savePath + '" data-url="' + (ops._uri + obj.savePath) + '">';
          s += '<span class="tag ' + findType(obj.suffix) + '">&nbsp;</span>';
          s += '<span class="name" title="' + obj.originalFilename + '">' + obj.originalFilename + '</span>';
          s += '<span class="control">(<a href="' + (ops._uri + obj.savePath) + '" style="color:#366dd1;" target="_blank">下载</a>&nbsp;|&nbsp;<a href="javascript:;" class="remove" style="color:#c00">删除</a>)</span>';
          s += '</li>';
          o.find('.file_list').append(s);
          //绑定删除函数
          o.find('a.remove').unbind('click').click(function () {
            $(this).parents('li').remove();
          });
          if (ops._drag) {
            o.find('.file_list').sortable({
              'placeholder': 'ui-state-highlight'
            });
            o.find('.file_list').disableSelection();
          };
        } else {
          alert(data.d);
        };
      },
      onUploadError: ops._onUploadError || function (file, errorCode, errorMsg, errorString) {
        alert('The file ' + file.name + ' could not be uploaded: ' + errorString);
      },
    }

    if (!$()._isFlash()) {
      var uploader = $(this).Huploadify(_datas);
    } else {
      var uploader = $(ops._file).uploadify(_datas);
    }
    if (!_datas.auto) {
      $.fn.fileLoaderUploadify = function(data){
        if (!$()._isFlash()) {
          uploader.formData = $.extend(_datas.formData,data);
          uploader.allUpload();
        }else{
          $(ops._file).uploadify('settings','formData',data);
          $(ops._file).uploadify('upload', '*');
        }
      }
    }
    // var uploader = $(ops._file).uploadify(datas);
  };

  //获取文件上传列表信息（名称/地址）
  $.fn.getFileList = function (type) {
    var s = '';
    switch (type) {
      case 'name':
        //获取名称列表
        $(this.selector).find('li').each(function () {
          s += $(this).data('name');
          s += ',';
        });
        break;
      case 'path':
        //获取地址列表
        $(this.selector).find('li').each(function () {
          s += $(this).data('path');
          s += ',';
        });
        break;
    };
    return s.substring(0, s.length - 1);
  };
  // html5上传
  $.fn.Huploadify = function (opts) {
    $(opts.file).css('display', 'none');
    var itemTemp = '<div id="${fileID}" class="uploadify-queue-item"><div class="uploadify-progress"><div class="uploadify-progress-bar"></div></div><span class="up_filename" style="margin-left:8px;">${fileName}</span><span class="uploadbtn">上传</span><span class="delfilebtn" style="color:red;margin-left:8px;">删除</span></div>';
    var defaults = {
      fileTypeExts: opts.fileTypeExts || '*.*',//允许上传的文件类型，格式'*.jpg;*.doc'
      uploader: '',//文件提交的地址
      auto: opts.auto,//是否开启自动上传
      method: 'post',//发送请求的方式，get或post
      multi: opts.multi,//是否允许选择多个文件
      formData: opts.formData || null,//发送给服务端的参数，格式：{key1:value1,key2:value2}
      fileObjName: opts.fileObjName || 'file',//在后端接受文件的参数名称，如PHP中的$_FILES['file']
      fileSizeLimit: opts.fileSizeLimit,//允许上传的文件大小，单位KB
      showUploadedPercent: true,//是否实时显示上传的百分比，如20%
      showUploadedSize: false,//是否实时显示已上传的文件大小，如1M/2M
      buttonText: '选择文件',//上传按钮上的文字
      removeTimeout: 1000,//上传完成后进度条的消失时间
      itemTemplate: itemTemp,//上传队列显示的模板
      onUploadStart: opts.onUploadStart || null,//上传开始时的动作
      onUploadSuccess: opts.onUploadSuccess || null,//上传成功的动作
      onUploadComplete: null,//上传完成的动作
      onUploadError: null, //上传失败的动作
      onInit: null,//初始化时的动作
      onCancel: null,//删除掉某个文件后的回调函数，可传入参数file
    }
    var option = $.extend(defaults, opts);
    
    //将文件的单位由bytes转换为KB或MB，若第二个参数指定为true，则永远转换为KB
    var formatFileSize = function (size, byKB) {
      if (size > 1024 * 1024 && !byKB) {
        size = (Math.round(size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
      }
      else {
        size = (Math.round(size * 100 / 1024) / 100).toString() + 'KB';
      }
      return size;
    }
    var fileSize__ = function (size) {
      var arr = ['KB', 'MB', "GB"]
      var unit = size.substring(size.length - 2, size.length).toUpperCase()
      var index = $.inArray(unit, arr)
      if (index != -1) {
        var num = Math.pow(1024, index) * size.substring(0, size.length - 2)
        return num;
      } else {
        alert('单位设置错误')
      }
    }
    //根据文件序号获取文件
    var getFile = function (index, files) {
      for (var i = 0; i < files.length; i++) {
        if (files[i].index == index) {
          return files[i];
        }
      }
      return false;
    }
    //将输入的文件类型字符串转化为数组,原格式为*.jpg;*.png
    var getFileTypes = function (str, state) {
      var result = [];
      var arr =
        [
          { key: '*.3gpp', v: 'audio/3gpp, video/3gpp' }
          , { key: '*.ac3', v: 'audio/ac3' }
          , { key: '*.asf', v: 'allpication/vnd.ms-asf' }
          , { key: '*.au', v: 'audio/basic' }
          , { key: '*.css', v: 'text/css' }
          , { key: '*.csv', v: 'text/csv' }
          , { key: '*.doc', v: 'application/msword' }
          , { key: '*.dot', v: 'application/msword' }
          , { key: '*.dtd', v: 'application/xml-dtd' }
          , { key: '*.dwg', v: 'image/vnd.dwg' }
          , { key: '*.dxf', v: 'image/vnd.dxf' }
          , { key: '*.gif', v: 'image/gif' }
          , { key: '*.htm', v: 'text/html' }
          , { key: '*.html', v: 'text/html' }
          , { key: '*.jp2', v: 'image/jp2' }
          , { key: '*.jpe', v: 'image/jpeg' }
          , { key: '*.jpeg', v: 'image/jpeg' }
          , { key: '*.jpg', v: 'image/jpeg' }
          , { key: '*.js', v: 'text/javascript, application/javascript' }
          , { key: '*.json', v: 'application/json' }
          , { key: '*.mp2', v: 'audio/mpeg, video/mpeg' }
          , { key: '*.mp3', v: 'audio/mpeg' }
          , { key: '*.mp4', v: 'audio/mp4, video/mp4' }
          , { key: '*.mpeg', v: 'video/mpeg' }
          , { key: '*.mpg', v: 'video/mpeg' }
          , { key: '*.mpp', v: 'application/vnd.ms-project' }
          , { key: '*.ogg', v: 'application/ogg, audio/ogg' }
          , { key: '*.pdf', v: 'application/pdf' }
          , { key: '*.png', v: 'image/png' }
          , { key: '*.pot', v: 'application/vnd.ms-powerpoint' }
          , { key: '*.pps', v: 'application/vnd.ms-powerpoint' }
          , { key: '*.ppt', v: 'application/vnd.ms-powerpoint' }
          , { key: '*.rtf', v: 'application/rtf, text/rtf' }
          , { key: '*.svf', v: 'image/vnd.svf' }
          , { key: '*.tif', v: 'image/tiff' }
          , { key: '*.tiff', v: 'image/tiff' }
          , { key: '*.txt', v: 'text/plain' }
          , { key: '*.wdb', v: 'application/vnd.ms-works' }
          , { key: '*.wps', v: 'application/vnd.ms-works' }
          , { key: '*.xhtml', v: 'application/xhtml+xml' }
          , { key: '*.xlc', v: 'application/vnd.ms-excel' }
          , { key: '*.xlm', v: 'application/vnd.ms-excel' }
          , { key: '*.xls', v: 'application/vnd.ms-excel' }
          , { key: '*.xlt', v: 'application/vnd.ms-excel' }
          , { key: '*.xlw', v: 'application/vnd.ms-excel' }
          , { key: '*.xml', v: 'text/xml, application/xml' }
          , { key: '*.zip', v: 'aplication/zip' }
          , { key: '*.xlsx', v: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }

        ]
      var arr1 = str.split(";");
      if (state) {
        if (str.indexOf('*.*') != -1) {
          for (var i = 0; i < arr.length; i++) {
            result.push(arr[i].key.split('.')[1]);
          }
          return ['*.*']
        } else {
          for (var i = 0, len = arr1.length; i < len; i++) {
            for (var j = 0; j < arr.length; j++) {
              if (arr[j].key == arr1[i]) {
                result.push(arr[j].key.split('.')[1]);
              }
            }
          }
          return result;
        }
      }
      if (str.indexOf('*.*') != -1) {
        for (var i = 0; i < arr.length; i++) {
          result.push(arr[i].v);
        }
        return ['*.*']
      }
      for (var i = 0, len = arr1.length; i < len; i++) {
        for (var j = 0; j < arr.length; j++) {
          if (arr[j].key == arr1[i]) {
            result.push(arr[j].v);
          }
        }
      }
      return result;
    }
    


    // this.each(function () {
      var _this = $(this);
      //先添加上file按钮和上传列表
      var instanceNumber = $('.uploadify').length + 1;
      var inputStr = '<input id="select_btn_' + instanceNumber + '" class="selectbtn" style="display:none;" type="file" name="fileselect[]"';
      inputStr += option.multi ? ' multiple' : '';
      inputStr += ' accept="';
      inputStr += getFileTypes(option.fileTypeExts).join(",");
      inputStr += '"/>';
      inputStr += '<a id="file_upload_' + instanceNumber + '-button" href="javascript:void(0)" style="width:' + option.width + 'px;height:' + option.height + 'px;';
      inputStr += 'line-height:' + option.height + 'px ;" class="uploadify-button html5">' + option.buttonText;
      inputStr += '</a>';

      // inputStr += '<style type="text/css">';
      // inputStr += '.uploadify-button{color: #fff;backgr ound-color: #417dea;border: 1px solid #366dd1;border-radius: 2px;background-image: none;font-weight: bold;background:#505050;opacity: 0.9;}';
      // inputStr += '.uploadify-button:hover{background: none;background-color: #417dea;opacity: 1;color:#fff;text-decoration: none;}';
      // inputStr += '</style>';

      var uploadFileListStr = '<div id="file_upload_' + instanceNumber + '-queue" class="uploadify-queue"></div>';
      // _this.append(inputStr + uploadFileListStr);
      $(option.file).before(inputStr + uploadFileListStr);

      //创建文件对象
      var fileObj = {
        fileInput: _this.parent().find('.selectbtn'),				//html file控件
        uploadFileList: _this.parent().find('.uploadify-queue'),
        url: option.uploader,						//ajax地址
        fileFilter: [],					//过滤后的文件数组
        formData:option.formData,
        filter: function (files) {		//选择文件组的过滤方法
          if (files.length > option.queueSizeLimit) {
            alert('文件数量超出限制！');
            return;
          }
          var arr = [];
          var typeArray = getFileTypes(option.fileTypeExts);
          if (typeArray.length > 0) {
            for (var i = 0, len = files.length; i < len; i++) {
              var thisFile = files[i];
              if (parseInt(formatFileSize(thisFile.size, true)) > fileSize__(option.fileSizeLimit)) {
                alert('文件' + thisFile.name + '大小超出限制！');
                continue;
              }
              if (option.fileTypeExts.indexOf('*.*') >= 0 || $.inArray(thisFile.name.split('.').pop(), getFileTypes(defaults.fileTypeExts, 1)) >= 0) {
                arr.push(thisFile);
              }
              else {
                alert('文件' + thisFile.name + '类型不允许！');
              }
            }
          }
          return arr;
        },
        //文件选择后
        onSelect: function (files) {
          var len = files.length;
          if (this.uploadFileList.find('.uploadify-queue-item').length + files.length > option.queueSizeLimit) {
            alert('上传数目过多');
            len = option.max - _this.find('li').length;
          }
          for (var i = 0; i < len; i++) {
            var file = files[i];
            //处理模板中使用的变量

            var $html = $(option.itemTemplate.replace(/\${fileID}/g, 'fileupload_' + instanceNumber + '_' + file.index + '_' + file.size + '_' + file.lastModified).replace(/\${fileName}/g, file.name).replace(/\${fileSize}/g, formatFileSize(file.size)).replace(/\${instanceID}/g, _this.attr('id')));
            //如果是自动上传，去掉上传按钮
            if (option.auto) {
              $html.find('.uploadbtn').remove();
            }

            if (_this.find('li').length < option.max) {
              this.uploadFileList.append($html);
            }

            //判断是否显示已上传文件大小
            if (option.showUploadedSize) {
              var num = '<span class="progressnum"><span class="uploadedsize">0KB</span>/<span class="totalsize">${fileSize}</span></span>'.replace(/\${fileSize}/g, formatFileSize(file.size));
              $html.find('.uploadify-progress').after(num);
            }

            //判断是否显示上传百分比	
            if (option.showUploadedPercent) {
              var percentText = '<span class="up_percent">0%</span>';
              $html.find('.uploadify-progress').after(percentText);
            }
            //判断是否是自动上传
            if (option.auto) {
              this.funUploadFile(file);
            }
            else {
              //如果配置非自动上传，绑定上传事件
              // $(option.autoBtn).on('click', (function (file) {
              //   return function () {
              //     fileObj.funUploadFile(file);
              //   }
              // })(file));
              
            }
            //为删除文件按钮绑定删除文件事件
            $html.find('.delfilebtn').on('click', (function (fileT) {
              return function () { fileObj.funDeleteFile('' + fileT.index + fileT.size + fileT.lastModified); }
            })(file));
          }


        },
        allUpload:function(){
          for(var i=0;i<fileObj.fileFilter.length;i++){
            fileObj.funUploadFile(fileObj.fileFilter[i])
          }
        },
        onProgress: function (file, loaded, total) {
          var eleProgress = _this.parent().find('#fileupload_' + instanceNumber + '_' + file.index + '_' + file.size + '_' + file.lastModified + ' .uploadify-progress');
          var percent = (loaded / total * 100).toFixed(2) + '%';
          if (option.showUploadedSize) {
            eleProgress.nextAll('.progressnum .uploadedsize').text(formatFileSize(loaded));
            eleProgress.nextAll('.progressnum .totalsize').text(formatFileSize(total));
          }
          if (option.showUploadedPercent) {
            eleProgress.nextAll('.up_percent').text(percent);
          }
          eleProgress.find('.uploadify-progress-bar').css('width', percent);
        },		//文件上传进度

        /* 开发参数和内置方法分界线 */

        //获取选择文件，file控件
        funGetFiles: function (e) {
          // 获取文件列表对象
          var files = e.target.files;
          //继续添加文件
          files = this.filter(files);
          for (var i = 0, len = files.length; i < len; i++) {
            this.fileFilter.push(files[i]);
          }

          this.funDealFiles(files);
          return this;
        },

        //选中文件的处理与回调
        funDealFiles: function (files) {
          var fileCount = _this.find('.uploadify-queue .uploadify-queue-item').length;//队列中已经有的文件个数
          for (var i = 0, len = files.length; i < len; i++) {
            files[i].index = ++fileCount;
            files[i].id = files[i].index;
          }
          //执行选择回调
          this.onSelect(files);

          return this;
        },

        //删除对应的文件
        funDeleteFile: function (index) {
          for (var i = 0, len = this.fileFilter.length; i < len; i++) {
            var file = this.fileFilter[i];
            if ('' + file.index + file.size + file.lastModified == index) {
              this.fileFilter.splice(i, 1);
              _this.parent().find('#fileupload_' + instanceNumber + '_' + file.index + '_' + file.size + '_' + file.lastModified).fadeOut(800, function () {
                _this.parent().find('#fileupload_' + instanceNumber + '_' + file.index + '_' + file.size + '_' + file.lastModified).remove()
              });
              option.onCancel && option.onCancel(file);
              break;
            }
          }
          return this;
        },
        funChangeFormData: function () {
          this.formData = {a:1,b:3,c:3333}
        },
        //文件上传
        funUploadFile: function (file) {
          var fileIn = false;
          for (var i = 0; i < fileObj.fileFilter.length; i++) {
            if (file.name == fileObj.fileFilter[i].name) {
              fileIn = true;
            }
          }
          if(fileIn != true) return;
          var xhr = false;
          try {
            xhr = new XMLHttpRequest();//尝试创建 XMLHttpRequest 对象，除 IE 外的浏览器都支持这个方法。
          } catch (e) {
            xhr = ActiveXobject("Msxml12.XMLHTTP");//使用较新版本的 IE 创建 IE 兼容的对象（Msxml2.XMLHTTP）。
          }

          if (xhr.upload) {
            // 上传中
            xhr.upload.addEventListener("progress", function (e) {
              var state = false
              for (var i = 0; i < fileObj.fileFilter.length; i++) {
                if (file.name == fileObj.fileFilter[i].name) {
                  state = true
                }
              }
              if (state) {
                fileObj.onProgress(file, e.loaded, e.total);
              } else {
                xhr.abort()
              }
            }, false);

            // 文件上传成功或是失败
            xhr.onreadystatechange = function (e) {
              if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                  //校正进度条和上传比例的误差
                  var datas = JSON.parse(e.target.responseText);

                  var thisfile = _this.parent().find('#fileupload_' + instanceNumber + '_' + file.index + '_' + file.size + '_' + file.lastModified);
                  thisfile.find('.uploadify-progress-bar').css('width', '100%');
                  option.showUploadedSize && thisfile.find('.uploadedsize').text(thisfile.find('.totalsize').text());
                  option.showUploadedPercent && thisfile.find('.up_percent').text('100%');

                  option.onUploadSuccess && option.onUploadSuccess(file, xhr.responseText);
                  //在指定的间隔时间后删掉进度条
                  setTimeout(function () {
                    _this.parent().find('#fileupload_' + instanceNumber + '_' + file.index + '_' + file.size + '_' + file.lastModified).fadeOut(600, function () {
                      _this.parent().find('#fileupload_' + instanceNumber + '_' + file.index + '_' + file.size + '_' + file.lastModified).remove();
                    });
                  }, option.removeTimeout);
                  for (var i = 0; i < fileObj.fileFilter.length; i++) {
                    if (file.name == fileObj.fileFilter[i].name) {
                      fileObj.fileFilter.splice(i, 1);
                    }
                  }
                  $(option.autoBtn).off("click")
                } else {
                  option.onUploadError && option.onUploadError(file, xhr.responseText);
                }
                option.onUploadComplete && option.onUploadComplete(file, xhr.responseText);
                //清除文件选择框中的已有值
                fileObj.fileInput.val('');
              }
            };

            option.onUploadStart && option.onUploadStart();
            // 开始上传
            xhr.open(option.method, this.url, true);
            xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            var fd = new FormData();
            fd.append(option.fileObjName, file);
            if (option.formData) {
              for (key in this.formData) {
                fd.append(key, this.formData[key]);
              }
            }

            xhr.send(fd);
          }


        },

        init: function () {
          //文件选择控件选择
          if (this.fileInput.length > 0) {
            this.fileInput.change(function (e) {
              fileObj.funGetFiles(e);
            });
          }
          //点击上传按钮时触发file的click事件
          _this.parent().find('.uploadify-button').on('click', function () {
            _this.parent().find('.selectbtn').trigger('click');
          });

          option.onInit && option.onInit();
        }
      };

      //初始化文件对象
      fileObj.init();
      return fileObj;
    // });
  }
  $.fn.tabTree = function (url, treeId, treeContentId, btnId, btnImg1, btnImg2, selectId, selectChangeFun) {

    var selectState = true;
    $('#' + btnId).on('click', function () {
      if (!selectState && $('#' + treeId).html() == '') return
      selectState = !selectState;
      $('#' + btnId).css('background', selectState ? 'url(' + btnImg1 + ')' : 'url(' + btnImg2 + ')')
      $('#' + treeId).toggle(20, function () {
        $('#' + treeContentId).css({ 'margin-left': !selectState ? '0' : $('#' + treeId).innerWidth() + 10 })
      });
    })
    if (selectState) {
      $('#' + btnId).trigger("click");
    }
    $('#' + selectId).on('change', function (e) {
      //console.log($(this).children('option:selected').attr('data-id'))
      if (selectChangeFun) {
        selectChangeFun(e, 'treeId', {
          name: $(this).children('option:selected').val(),
          id: $(this).children('option:selected').attr('data-id'),
          extras: {
            code: $(this).children('option:selected').attr('data-code')
          }
        });
        return;
      }
    })

    function selectData(data) {
      var index = 0, kone = '';
      var _html = '';
      _html += optionHtml(data, kone);

      function optionHtml(data, kone) {
        index++;
        kone += '&nbsp;&nbsp;';
        var _html = '';
        for (var i = 0; i < data.length; i++) {
          _html += '<option value="' + data[i].name + '"  data-id="' + data[i].id + '" ';
          _html += ' data-code="' + data[i].extras.code + '">' + kone + data[i].name + '</option>';
          if (data[i].children && data[i].children.length > 0) {
            _html += optionHtml(data[i].children, kone);
          }
        }
        return _html;
      }


      $('#' + selectId).html(_html);
      $('#' + selectId).each(function (index, el) {
        selectbox(this);
      });
      $("#selectData").trigger("change");
    }

    //初始化树
    $.post(url, {}, function (data) {
      if (!selectState) {
        setTimeout(function () {
          initTree(data);
        }, 200);
      }
      selectData(data);
    }, "json");
    /*初始化各项设置*/
    function initTree(zNodes) {
      //初始化树
      var setting = {
        async: {
          url: getAsyncUrl,
          enable: true
        },
        callback: {
          onClick: selectChangeFun
        }
      };
      treeObj = $("#" + treeId).createTree(setting, zNodes, function () { }, 999);
    }
  }


})(jQuery)


$(function () {
  //标签页
  $('[data-toggle=tab]').each(function () {
    var $tabsBtn = $(this).find('.tabs-btn');
    $tabsBtn.bind('click', $tabsBtn, changeTab);
  });
  //标签
  $(document).on('click', '.tags .close', function () {
    $(this).parents('.tags').remove();
  });
});

/*
 * 获取文件名后缀
 * @param  {String} string 文件名全称
 * @return {string} 文件后缀
*/
function findLast(string) {
  var index = string.indexOf('.');
  return string.substring(index + 1, string.length);
};

/*
 * 根据后缀名称识别文件mimetype
 * @param  {String} string 文件后缀类型
 * @return {string} result 文件类型名称(图片sprite样式名称)
*/
function findType(string) {
  var result = '';
  switch (string) {
    case 'doc':
      //word文档2003
      result = 'fileType_0';
      break;
    case 'docx':
      //word文档2007
      result = 'fileType_0';
      break;
    case 'txt':
      //text文本文件
      result = 'fileType_1';
      break;
    case 'ppt':
      //ppt文档
      result = 'fileType_2';
      break;
    case 'xls':
      //excel文档
      result = 'fileType_3';
      break;
    case 'xlsx':
      //excel文档
      result = 'fileType_3';
      break;
    default:
      result = 'fileType_default';
      break;
  }
  return result;
}



function changeTab(event) {
  event.preventDefault();

  event.data.removeClass('selected');
  $(this).addClass('selected');

  $($(this).attr('href')).siblings().hide()
    .end().show();
}

/**
 * 显示提示
 * @param  {String} tipString 提示字符串
 * @param  {[type]} type      success 绿色 danger 红色 info 蓝色 warning 黄色
 */
function tip(tipString, type) {
  var $dom = $(
    '<div class="dialog alert-tip alert alert-' + type + '">' +
    '<div>' + tipString + '</div>' +
    '</div > '
  );
  var offset = '';

  $('body').append($dom);
  offset = _getCenterPoint($dom);

  $dom.show().css({
    top: 15,
    left: offset.left
  });

  window.setTimeout(function () {
    $dom.fadeOut('fast', function () {
      $dom.remove();
    });
  }, 2000);
}

/**
 * 显示iframe
 * @param  {String} title  标题
 * @param  {String} url    url地址
 * @param  {Number} width  宽度
 * @param  {Number} height 高度
 * @return {Number} index  层级
 */
function showIframe(title, url, width, height) {
  if (typeof $.layer !== 'undefined') {
    if (!title) {
      title = false;
    }
    return $.layer({
      type: 2,
      title: title,
      maxmin: true,
      shadeClose: true,
      area: [width + 'px', height + 'px'],
      iframe: {
        src: url
      }
    });
  }
}

/**
 * 显示dom
 * @param  {String} title  标题
 * @param  {Object} dom    dom
 * @param  {Number} width  宽度
 * @param  {Number} height 高度
 * @return {Number} index  层级
 */
function showDom(title, dom, width, height) {
  if (typeof $.layer !== 'undefined') {
    if (!title) {
      title = false;
    }
    $(dom).find('.form-wrap').width(width - 42).height(height - 77);
    return $.layer({
      type: 1,
      title: title,
      maxmin: false,
      shadeClose: true,
      area: [width + 'px', height + 'px'],
      page: {
        dom: dom
      }
    });
  }
}

/**
 * 显示alert
 * @param  {String} msg    字符串
 * @param  {Number} width  宽度
 * @param  {Number} height 高度
 * @return {Number} index  层级
 */
function showAlert(msg, yes, no) {
  if (typeof $.layer !== 'undefined') {
    return $.layer({
      shade: [0.5, '#000'],
      area: ['auto', 'auto'],
      dialog: {
        msg: msg,
        type: -1,
        btns: 2,
        btn: ['确定', '取消'],
        yes: yes
      }
    });
  }
}



/**
 * 标签
 * @param  {[type]} config [description]
 * @return {[type]}        [description]
 */
function tags(config) {

}

/**
 * 显示遮罩
 */
function showShade() {
  if ($('body .shade').length) {
    return false;
  } else {
    $('body').append('<div class="shade"></div>')
  }
}
/**
 * 隐藏遮罩
 */
function hideShade() {
  $('body .shade').remove();
}

function _getCenterPoint($dom) {
  return {
    left: $(document).width() / 2 - $dom.outerWidth() / 2,
    top: $(document).height() / 2 - $dom.outerHeight() / 2
  };
}

//弹出内容层
function popupLayer(content, title, size, btn, yesCallback, cancelCallback, successCallback) {
  var popupIndex = layer.open({
    type: $(content).length ? 1 : 2,
    title: title,
    content: $(content).length ? $(content) : content,
    area: size || ["900px", "500px"],
    closeBtn: 1,
    btn: btn,
    yes: function (index, layero) {

      if (yesCallback && $.type(yesCallback) == "function") {
        yesCallback(index, layero);
      }

    },
    cancel: function (index) {

      if (cancelCallback && $.type(cancelCallback) == "function") {
        cancelCallback(index)
      }

    },
    success: function (layero, index) {
      /*//缓存目前选中的数据，用于关闭时重置选择
      oldSelectedItem = me.getSelectedItem();*/
      if (successCallback && $.type(successCallback) == "function") {
        successCallback(layero, index)
      }
    }
  });
  /*}, 500);*/

  return popupIndex;
}


function consoleLog(content) {

  if (window["console"]) {
    console.log(content)
  }
}

//联动化组件
function gridPanelviewAdv(obj) {
  /*初始化表格*/
  var grid = obj.gridTarget.grid({
    store: obj.gridData,
    tool: {
      pagingBar: true
    },
    event: {
      onSelectAll: function (list) {
        //console.log(list)
        //全选后同步页面缓存数组
        setTimeout(function () {

          if (list.length == 0) {
            //全部取消,清空数组
            obj.tempList = [];
          } else {
            var _fl = false;
            for (var i = 0, l = list.length; i < l; i++) {
              _fl = false;
              for (var o = 0, p = obj.tempList.length; o < p; o++) {
                if (obj.tempList[o].id == list[i].id) {
                  _fl = true;
                };
              };

              if (!_fl) {
                //缓存中不存在该元素
                var x = {};
                x.id = list[i].id;
                x.name = list[i].name;
                obj.tempList.push(x);
              };
            };
          };
        });

      },
      onLoadCallback: function () {
        setTimeout(function () {
          //grid.selectRecord(_list);
          //绑定点击
          $('input.checkbox:not(.selectAll)').unbind('click').click(function () {
            var o = $(this),
              _t = grid.getRowDataByDom(o),
              x = {};

            x.id = _t.data.id;
            x.name = _t.data.name;

            if (o.prop('checked')) {
              var flag = false;
              for (var i = 0, l = obj.tempList.length; i < l; i++) {
                if (obj.tempList[i].id == x.id) {
                  //查找到项目
                  flag = true;
                  break;
                };
              };

              if (!flag) {
                obj.tempList.push(x);
              };
            } else {
              for (var i = 0, l = obj.tempList.length; i < l; i++) {
                if (obj.tempList[i].id == x.id) {
                  //查找到项目
                  obj.tempList.splice(i, 1);
                  break;
                };
              };

            };
            //console.log(obj.tempList);
          });
        }, 0);
      },
      callback: function (gd) {
        setTimeout(function () {
          //grid.selectRecord(_list);
          //辅助功能（checkbox点击）
          console.log(obj.tempList)

        }, 0);
      }
    },
    columns: obj.columns
  });
  /*panelviewport*/
  var panelviewport = obj.panelTarget.panelview({
    store: {
      data: obj.tempList
    },
    showName: obj.showName,
    callback: {
      yesCallback: function ($self, panelO) {
        //alert('yes')
        var _list = panelO.getAllData(),
          _sid = '',
          _sname = '';
        for (var i = 0, l = _list.length; i < l; i++) {
          _sid += _list[i].id;
          _sid += ',';
          _sname += _list[i].name;
          _sname += ',';
        };
        _sid = _sid.substring(0, _sid.length - 1);
        _sname = _sname.substring(0, _sname.length - 1);
        var _temp = {};
        _temp.ids = _sid;
        _temp.names = _sname;
        //返回
        //console.log('id:' + _sid + ';name:' + _sname);
        //obj.outerNames.val(_sname);
        //obj.outerIds.val(_sid);
        obj.outer(_temp);
        if (obj.autoClose) {
          window.parent.closeAll();
        };
      },
      noCallback: function ($self, self) {
        self.cleanNode();
        var $selectAll = grid.$me.find('.selectAll');
        if ($selectAll.is(':checked')) {
          $selectAll.trigger('click');
        } else {
          grid.$me.find('.checkbox:checked').trigger('click');
        }
      },
      removeClick: function ($self, $currentNode, panelO) {
        //panelO.removeNode($currentNode);
        //console.log($currentNode.data('id'))
        panelO.removeNode($currentNode);
        for (var i = 0, l = obj.tempList.length; i < l; i++) {
          if (obj.tempList[i].id == $currentNode.data('id')) {
            obj.tempList.splice(i, 1);
            break;
          };
        };
        //console.log(obj.tempList);

      }
    }
  });

  // gridPanelview([grid, panelviewport]);

  return gridPanelview([grid, panelviewport]);
};

//表格视图封装
function gridPanelview(controllerO) {
  var gridO = controllerO[0];
  var panelO = controllerO[1];

  var $grid = gridO.$me;
  var $panel = panelO.$me;

  gridO.config.event.onSelectAll = function (gd) {
    console.log('123213')
  }

  //表格多选框 点击改变 事件
  $grid.delegate(":checkbox:not(.selectAll)", "change", function () {
    //todo 更改数据结构
    var currentGridData = gridO.getRowDataByDom($(this)).data;
    //不变动表格原数据，复制成为新的数据
    var panelData = panelO.cloneData(currentGridData, function (cloneData, filterData, me) {
      //如果id不存在则将表格的_id复制一份给面板的id
      if (!cloneData.id) {
        cloneData.id = cloneData._id;
      }
    });

    var nodeId = panelData.id;
    if (this.checked) {
      //选中状态生成视图项节点
      //容错：面板中已有该选项，则不再生成
      if (nodeId && panelO.getNodeById(nodeId).length > 0) { } else {
        panelO.addNode(panelData);
      }
    } else {
      //取消选中状态时移除视图项节点
      panelO.removeNode(nodeId)
    }
  });

  //TODO表格 全选按钮事件
  $grid.delegate(".selectAll", "change", function () {
    //console.log($grid.next(".table-bottom-bar").find(".pagination").find(""))
    var checkbox = $grid.find(":checkbox").not(".selectAll");
    checkbox.each(function () {
      $(this).change();
    })
  });

  //TODO分页按钮事件
  $grid.next(".table-bottom-bar").delegate(".pagination", "click", function () { });

  //面板移除事件
  panelO.$content.delegate("[data-role='remove']", "click", function (event) {
    var id = panelO.getDataById($(this).parents('[data-role="node"]')).id
    $grid.find(":checkbox").not(".selectAll").filter("#" + id).prop("checked", false);
    $grid.find(".selectAll").prop("checked", false);
    return true;
  });

  //确认按钮事件的重新绑定
  panelO.$control.find("[data-role='yes']").click(function () {
    var data = panelO.getAllData(),
      s = '',
      d = '';
    console.log(data);
    for (i in data) {
      s += data[i].id + ',';
      d += data[i].name + ',';
    };
    console.log(s.substring(0, s.length - 1));
    console.log(d.substring(0, d.length - 1));
  });

  return gridO;
};

//列表弹出视图封装
function SelectBoxPanelview(controllerO) {
  var sbO = controllerO[0];
  var panelO = controllerO[1];

  var $sb = sbO.$me;
  var $panel = panelO.$me;

  //重载面板配置
  if (!panelO.config._userDefined) {
    var panelOsetting = {
      //功能配置
      view: {
        //默认启用控制栏
        enabledcontrol: false,

        //自定义内容区html格式
        nodeFormater: function (nodeData) {
          //return 每一项的格式
          //根据不同的显示要求生成项html
          if (sbO.config.view.mainShow == "image") {
            return '<div><img src="' + nodeData.image + '" /></div>';
          } else if (sbO.config.view.mainShow == "text") {
            return '<div><span>' + nodeData.name + '</span></div>';
          } else {
            //名称如果未填写容错处理放置空白符
            if (!nodeData.name) {
              nodeData.name = "&nbsp;"
            }

            var imageHtml = "";
            if (nodeData.image) {
              imageHtml = '<img src="' + nodeData.image + '" alt="' + nodeData.name + '" title="' + nodeData.name + '">';
            }

            return "<div>" + imageHtml + '<span>' + nodeData.name + '</span></div>';
          }
        }
      }
    };
    panelO.load(panelOsetting, function ($addNode, panelO) {
      panelO.$me.prepend('<div class="heading">您目前的选择：</div>')
    })
  }

  //初始化视图面板，选中选项框已选中的数据
  panelO.addNode(panelO.cloneData(sbO.getSelectedData()), function ($addNode, panelO) {
    panelO.cancelSelectedNode($addNode);
  });

  //事件侦听：
  //选项框点击，面板视图出现相关信息
  sbO.$content.delegate("[data-role='node']", "click", function (event) {
    //获取节点数据
    var currentSBData = sbO.getDataById($(this));

    //直接在面板里显选中示数据
    if (currentSBData.state == "selected" && !(currentSBData.id && panelO.getNodeById(currentSBData.id).length > 0)) {

      if (!sbO.config.view.enabledMultiple) {
        panelO.cleanAllNode();
      }

      var cloneData = panelO.cloneData(currentSBData);

      var $addnode = panelO.addNode(cloneData)
      panelO.cancelSelectedNode($addnode);

    } else if (currentSBData.state != "selected" && (currentSBData.id && panelO.getNodeById(currentSBData.id).length > 0)) {
      panelO.removeNode(currentSBData.id);
    }
  });

  //视图按钮移除点击事件
  panelO.$content.delegate("[data-role='remove']", "click", function (event) {
    var currentData = panelO.getDataById($(this).parents('[data-role="node"]'));

    var $sbNode = sbO.getNodeById(currentData.id);
    sbO.cancelSelectedNode($sbNode);

  });

}


//弹出框视图封装封装
function popupSelectBox(controllerO, content, title, size, btn, yesCallback, cancelCallback, successCallback) {

  var sbO = controllerO[0];
  var panelO = controllerO[1];
  var panelO2;
  if (controllerO[2]) {
    panelO2 = controllerO[2];
  }

  var $sb = sbO.$me;
  var $panel = panelO.$me;
  var $panel2 = panelO2 ? panelO2.me : null;

  //如果自定义了配置，则以用户配置为准，忽略此处
  //重载面板配置
  if (!panelO.config._userDefined) {
    var panelOsetting = {
      _userDefined: false,
      //功能配置
      view: {
        //默认启用控制栏
        enabledcontrol: false,
        //自定义内容区html格式
        nodeFormater: function (nodeData) {
          //return 每一项的格式
          //根据不同的显示要求生成项html
          if (sbO.config.view.mainShow == "image") {
            return '<div><img src="' + nodeData.image + '" /></div>';

          } else if (sbO.config.view.mainShow == "text") {
            return '<div><span>' + nodeData.name + '</span></div>';
          } else {
            //名称如果未填写容错处理放置空白符
            if (!nodeData.name) {
              nodeData.name = "&nbsp;"
            }

            var imageHtml = "";
            if (nodeData.image) {
              imageHtml = '<img src="' + nodeData.image + '" alt="' + nodeData.name + '" title="' + nodeData.name + '">';
            }

            return "<div>" + imageHtml + '<span>' + nodeData.name + '</span></div>';
          }
        }
      }
    };
    panelO.load(panelOsetting, function ($addNode, panelO) {
      $panel.prepend('<div class="placeholder">请选择</div><i class="selectbox-icon"></i>')
    })
  }

  //初始化视图面板，选中选项框已选中的数据
  panelO.addNode(panelO.cloneData(sbO.getSelectedData()), function ($addNode, panelO) {
    panelO.cancelSelectedNode($addNode);
    //若无增加项，则将placeholder显示出来
    if ($addNode.length <= 0) {
      $panel.find(".placeholder").show();
      panelO.$content.hide();
    } else {
      if (!sbO.config.view.enabledMultiple && panelO.getAllNode().length == 1) {
        panelO.$content.addClass("single");
      } else {
        panelO.$content.removeClass("single");
      }
      //一项时增加single属性
      panelO.cancelSelectedNode($addNode)
      $panel.find(".placeholder").hide();
      panelO.$content.show();
    }
  });

  //事件侦听：

  //视图按钮移除点击事件
  panelO.$content.delegate("[data-role='remove']", "click", function (event) {
    var currentData = panelO.getDataById($(this).parents('[data-role="node"]'));

    var $sbNode = sbO.getNodeById(currentData.id);
    sbO.cancelSelectedNode($sbNode);


    if (panelO2) {
      var $panelO2Node = panelO2.getNodeById(currentData.id);
      panelO2.removeNode($panelO2Node);
    }


    //视图区无选项时，显示placeholder
    if (panelO.getAllNode().length <= 0) {
      $panel.find(".placeholder").show();
      panelO.$content.hide();
    } else {
      //一项时增加single属性
      if (!sbO.config.view.enabledMultiple && panelO.getAllNode().length == 1) {
        panelO.$content.addClass("single");
      } else {
        panelO.$content.removeClass("single");
      }
      $panel.find(".placeholder").hide();
      panelO.$content.show();
    }



  });

  //如果选择框被隐藏，则默认为面板视图设置一个打开
  //面板框点击事件

  if ($sb.is(":hidden")) {
    $panel.bind("click", function () {

      $panel.addClass("focus");

      //使用layer打开层

      var $oldSelectedNode;

      var popupIndex = popupLayer(content, title, size, btn, function (index, layero) {

        //点击保存时可以获取当前选中的目标
        //显示在目标区域里
        //获取图标地址和图标名称,返回一个数组对象
        //暂存目前选中的数据
        //假如未开启视图面板自动显示，则显示一次
        var $getNode = sbO.getSelectedNode();
        panelO.cleanAllNode();


        //增项加：未复制数据，镜象引用

        var cloneData = panelO.cloneData(sbO.getSelectedData());
        var $addNode = panelO.addNode(cloneData);

        //视图区无选项时，显示placeholder
        if (panelO.getAllNode().length <= 0) {
          $panel.find(".placeholder").show();
          panelO.$content.hide();
        } else {
          if (!sbO.config.view.enabledMultiple && panelO.getAllNode().length == 1) {
            panelO.$content.addClass("single");
          } else {
            panelO.$content.removeClass("single");
          }
          //一项时增加single属性
          panelO.cancelSelectedNode($addNode)
          $panel.find(".placeholder").hide();
          panelO.$content.show();
        }

        $panel.removeClass("focus");

        if (yesCallback) {
          yesCallback(index, layero)
        } else {
          layer.close(popupIndex);
        }


      }, function (index) {

        //选框清空所有已选中项清空选择和数据
        sbO.cleanSelectedNode();

        sbO.selectNode($oldSelectedNode);

        if (panelO2) {
          if (sbO.config.view.enabledMultiple) {
            var $panelO2Node = panelO2.getNodeById(sbO.dataToArray(sbO.getDataById($oldSelectedNode, "id")));

            var $tempNode = panelO2.removeNode($panelO2Node);

            panelO2.cleanAllNode();

            panelO2.addNode(panelO2.getDataById($tempNode))
          } else {
            panelO2.cleanAllNode();


            var cloneData = panelO2.cloneData(sbO.getDataById($oldSelectedNode));

            var $addNode = panelO2.addNode(cloneData)

            panelO2.cancelSelectedNode($addNode)
          }

        }

        $panel.removeClass("focus");

        if (cancelCallback) {
          cancelCallback(index)
        }

      },
        function (layero, index) {
          //缓存目前选中的数据，用于关闭时重置选择
          $oldSelectedNode = sbO.getSelectedNode();
          if (successCallback) {
            successCallback(layero, index)
          }
        })

      event.stopPropagation();
    });
  }
}


//下拉列表
function droplist(controllerO) {
  var dlO = controllerO[0];
  var panelO = controllerO[1];
  var ncO;

  if (controllerO[2]) {
    ncO = controllerO[2];
  }

  var $dl = dlO.$me;
  var $panel = panelO.$me;
  var $nc = ncO ? ncO.me : null;

  //如果自定义了配置，则以用户配置为准，忽略此处
  //重载面板配置

  if (!panelO.config._userDefined) {
    var panelOsetting = {
      _userDefined: false,
      //功能配置
      view: {
        //默认启用控制栏
        enabledcontrol: false,
        //自定义内容区html格式
        nodeFormater: function (nodeData) {
          //return 每一项的格式
          //根据不同的显示要求生成项html
          if (dlO.config.view.mainShow == "image") {
            return '<div><img src="' + nodeData.image + '" /></div>';

          } else if (dlO.config.view.mainShow == "text") {
            return '<div><span>' + nodeData.name + '</span></div>';
          } else {
            //名称如果未填写容错处理放置空白符
            if (!nodeData.name) {
              nodeData.name = "&nbsp;"
            }

            var imageHtml = "";
            if (nodeData.image) {
              imageHtml = '<img src="' + nodeData.image + '" alt="' + nodeData.name + '" title="' + nodeData.name + '">';
            }

            return "<div>" + imageHtml + '<span>' + nodeData.name + '</span></div>';
          }
        }
      }
    };
    panelO.load(panelOsetting, function ($addNode, panelO) {
      $panel.prepend('<div class="placeholder">请选择</div><i class="selectbox-icon"></i>')
    })
  }

  //初始化视图面板，选中选项框已选中的数据
  panelO.addNode(panelO.cloneData(dlO.getSelectedData()), function ($addNode, panelO) {
    panelO.cancelSelectedNode($addNode);
    //若无增加项，则将placeholder显示出来
    if ($addNode.length <= 0) {
      $panel.find(".placeholder").show();
      panelO.$content.hide();
    } else {
      if (!dlO.config.view.enabledMultiple && panelO.getAllNode().length == 1) {
        panelO.$content.addClass("single");
      } else {
        panelO.$content.removeClass("single");
      }
      //一项时增加single属性
      panelO.cancelSelectedNode($addNode)
      $panel.find(".placeholder").hide();
      panelO.$content.show();
    }
  });

  //初始化UI
  $panel.parent().css({
    "position": "relative"
  });


  //侦听事件
  //面板点击事件
  if (dlO.config.view.enabled) {
    $panel.bind("click", function (event) {
      //删除其他同类空间焦点
      $(".select-panelview").removeClass("focus");
      event.stopPropagation();
      if (ncO) {
        if ($nc.is(":visible")) {
          $nc.hide();
        } else {
          $(".close-popup").hide();

          $panel.addClass("focus");
          $nc.show();
          $dl.show();

          $nc.css({
            "position": "absolute",
            "width": $panel.outerWidth() + "px",
            "left": 0,
            "zIndex": 1024
          });

          ncO.autohidedom.css({
            "zIndex": 1030
          });
        }
      } else {
        if ($dl.is(":visible")) {
          $dl.hide();
        } else {
          $(".close-popup").hide();

          $panel.addClass("focus");

          $dl.show();
          $dl.css({
            "position": "absolute",
            "width": $panel.innerWidth() + "px",
            "height": "288px",
            "overflowY": "auto",
            "left": 0,
            "zIndex": 1024
          });
        }
      }
    });

    //下拉列表点击，面板视图出现相关信息
    dlO.$content.delegate("[data-role='node']", "click", function (event) {
      //获取节点数据
      var currentSBData = dlO.getDataById($(this));

      //直接在面板里显选中示数据
      if (currentSBData.state == "selected" && !(currentSBData.id && panelO.getNodeById(currentSBData.id).length > 0)) {

        if (!dlO.config.view.enabledMultiple) {
          //单选
          panelO.cleanAllNode();
          $panel.removeClass("focus");

          $(".close-popup").hide();
        } else {
          event.stopPropagation();
          if (dlO.config.view.multipleSize && (dlO.config.view.multipleSize <= dlO.getSelectedNode().length)) {
            $panel.removeClass("focus");
            $(".close-popup").hide();
          }
        }

        var cloneData = panelO.cloneData(currentSBData);

        var $addnode = panelO.addNode(cloneData)
        panelO.cancelSelectedNode($addnode);

      } else if (currentSBData.state != "selected" && (currentSBData.id && panelO.getNodeById(currentSBData.id).length > 0)) {
        panelO.removeNode(currentSBData.id);
        event.stopPropagation();
      }

      //视图区无选项时，显示placeholder
      if (panelO.getAllNode().length <= 0) {
        $panel.find(".placeholder").show();
        panelO.$content.hide();
      } else {
        if (!dlO.config.view.enabledMultiple && panelO.getAllNode().length == 1) {
          panelO.$content.addClass("single");
        } else {
          panelO.$content.removeClass("single");
        }
        $panel.find(".placeholder").hide();
        panelO.$content.show();
      }

    });

    //视图按钮移除点击事件
    panelO.$content.delegate("[data-role='remove']", "click", function (event) {
      var currentData = panelO.getDataById($(this).parents('[data-role="node"]'));

      var $sbNode = dlO.getNodeById(currentData.id);
      dlO.cancelSelectedNode($sbNode);

      //视图区无选项时，显示placeholder
      if (panelO.getAllNode().length <= 0) {
        $panel.find(".placeholder").show();
        panelO.$content.hide();
      } else {
        //一项时增加single属性
        if (!dlO.config.view.enabledMultiple && panelO.getAllNode().length == 1) {
          panelO.$content.addClass("single");
        } else {
          panelO.$content.removeClass("single");
        }
        $panel.find(".placeholder").hide();
        panelO.$content.show();
      }
    });
  } else {
    $panel.addClass("disabled")
  }

  //点击空白区域关闭选框事件
  $("html").click(function () {
    $panel.removeClass("focus");

    $(".close-popup").hide();

  });

}


//返回自定义链接参数
function getUrlParams(searchString) {
  var params = {};

  var search = window.location.search;
  if (searchString) {
    search = searchString;
  }

  if (search && search.indexOf("?") > -1) {
    search = search.substring(search.indexOf("?") + 1, search.length);
    var tmps = search.split("&");
    for (var i = 0; i < tmps.length; i++) {
      var pair = tmps[i];
      var ttmps = pair.split("=");
      //可能会存在多值项，也可能不存在值，即ttmps<2
      //假如是转义过的字符串，则解码
      if (ttmps.length >= 2) {
        for (var j = 0; j < ttmps.length; j = j + 2) {
          if (ttmps[j + 1].indexOf('%') == 0) {
            params[ttmps[j]] = decodeURIComponent(ttmps[j + 1]);
          } else {
            params[ttmps[j]] = ttmps[j + 1];
          }
        }
      }
    }
  }
  return params;
}